import { getToken } from "@/utils/auth";
import axios from "axios";

// 读取配置文件中的统一路径前缀
const BASE_URL = process.env.REACT_APP_API;

const request = axios.create({
  withCredentials: true,
  baseURL: BASE_URL,
  timeout: 100000,
});

request.interceptors.request.use(
  (config) => {
    //不处理不需要token的接口
    if (!config.needToken) return config;

    const token = getToken();
    if (!token) {
      return Promise.reject(new Error("当前没有登录，请先登录！"));
    }
    const Authorization = config.headers?.Authorization || `Bearer ${token}`;
    if (config.headers) {
      config.headers.Authorization =
        config.headers.Authorization || `Bearer ${token}`;
    } else {
      config.headers = { Authorization };
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

request.interceptors.response.use(
  (res) => {
    return res.data;
  },
  (err) => {
    return Promise.reject(err);
  }
);
export default request;
